package com.alibaba.cirtus.ots.application.adapter.ability.facade.serviceV2.crm;

import com.alibaba.acm.shaded.com.google.common.collect.Lists;
import com.alibaba.acm.shaded.com.google.common.collect.Maps;
import com.alibaba.cirtus.ots.application.adapter.ability.model.enums.MnSAPStatus;
import com.alibaba.cirtus.ots.application.adapter.ability.model.response.CallApiRecordResponse;
import com.alibaba.citrus.ots.common.annotation.ProcessInvoker;
import com.alibaba.citrus.ots.common.util.SapAndCrmFieldDealUtils;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSONObject;
import com.epoch.app.crpricecenter.model.dto.SyncActivityClientRelationDataRequest;
import com.epoch.app.crpricecenter.model.dto.SyncActivityClientRelationDataResponse;
import com.epoch.app.crpricecenter.model.dto.SyncActivityTermGiftRelationDataRequest;
import com.epoch.app.crpricecenter.model.dto.SyncActivityTermGiftRelationDataResponse;
import com.epoch.app.crpricecenter.model.dto.SyncActivityTermItemRelationDataRequest;
import com.epoch.app.crpricecenter.model.dto.SyncActivityTermItemRelationDataResponse;
import com.epoch.app.crpricecenter.model.dto.SyncOperateJournalFlowDataRequest;
import com.epoch.app.crpricecenter.model.dto.SyncOperateJournalFlowDataResponse;
import com.epoch.app.crpricecenter.model.dto.SyncSegmentedActivityTermDataRequest;
import com.epoch.app.crpricecenter.model.dto.SyncSegmentedActivityTermDataResponse;
import com.epoch.app.crpricecenter.service.CrPriceCenterService;
import com.epoch.app.otsapplicationadaptersdk.crm.ActivityClientRelationDetail;
import com.epoch.app.otsapplicationadaptersdk.crm.ActivityDetailItemRelationDetail;
import com.epoch.app.otsapplicationadaptersdk.crm.ActivityGiftRelationDetail;
import com.epoch.app.otsapplicationadaptersdk.crm.MnCrmCommResponse;
import com.epoch.app.otsapplicationadaptersdk.crm.MnCrmCommSDO;
import com.epoch.app.otsapplicationadaptersdk.crm.MnCrmIf007Request;
import com.epoch.app.otsapplicationadaptersdk.crm.OperateJournalFlowDetail;
import com.epoch.app.otsapplicationadaptersdk.crm.SegmentedActivityTermDetail;
import com.epoch.app.otsapplicationadaptersdk.crmv2.mncrmif007v2.service.MnCrmIf007V2Service;
import com.epoch.app.otsapplicationadaptersdk.model.dto.MessageHeaderPassiveSDO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author hanguo
 * @date 2021/10/12
 * @Description crm请求平台同步坎级活动信息传输
 */
@Component
public class MnCrmIf007V2ServiceImpl implements MnCrmIf007V2Service {
    private static final Log log = Log.getLogger(MnCrmIf007V2ServiceImpl.class);

    @Resource
    private CrPriceCenterService crPriceCenterService;

    private static final String MESSAGE_ID = "messageId";

    private static final String DATA_SOURCE = "dataSource";

    @ProcessInvoker(remark = "MnCrmIf007V2Service", errorCode = "OTS-02-007-00-16-999", printLog = true)
    @Override
    public MnCrmCommResponse externalSynckLevelPromotionInfo(MnCrmIf007Request mnCrmIf007Request) {
        MnCrmCommResponse mnCrmCommResponse = new MnCrmCommResponse();
        mnCrmCommResponse.setMessageId(mnCrmIf007Request.getMessageHeader().getMessageId());
        mnCrmCommResponse.setInterfacePath(mnCrmIf007Request.getMessageHeader().getInterfacePath());
        MnCrmCommSDO mnCrmCommSDO = new MnCrmCommSDO();

        List<CallApiRecordResponse> callApiRecordResponses = Lists.newArrayList();

        //校验数据
        if(Objects.isNull(mnCrmIf007Request.getData())){
            mnCrmCommSDO.setResultType(MnSAPStatus.ERROR.getCode());
            mnCrmCommSDO.setResultMessage("请传数据!");
        }

        //数据来源记录
        MessageHeaderPassiveSDO messageHeader = mnCrmIf007Request.getMessageHeader();
        Map<String,String> features = Maps.newHashMap();
        if(Objects.nonNull(messageHeader)){
            //数据头信息id
            features.put(MESSAGE_ID,messageHeader.getMessageId());
            //数据来源 sap或者excel等
            features.put(DATA_SOURCE, messageHeader.getSender());
        }

        if (CollectionUtils.isNotEmpty(mnCrmIf007Request.getData().getActivityClientRelation())) {
            List<ActivityClientRelationDetail> activityClientRelation = mnCrmIf007Request.getData().getActivityClientRelation();
            //移除null 元素
            activityClientRelation.remove(null);

            if (CollectionUtils.isNotEmpty(activityClientRelation)) {
                activityClientRelation.forEach(item -> {

                    SyncActivityClientRelationDataRequest syncActivityClientRelationDataRequest = new SyncActivityClientRelationDataRequest();
                    BeanUtils.copyProperties(item, syncActivityClientRelationDataRequest);
                    syncActivityClientRelationDataRequest.setClientId(SapAndCrmFieldDealUtils.generateIdField(item.getClientId()));
                    syncActivityClientRelationDataRequest.setFeatures(JSONObject.toJSONString(features));
                    SyncActivityClientRelationDataResponse syncActivityClientRelationDataResponse = crPriceCenterService.syncActivityClientRelationData(syncActivityClientRelationDataRequest);


                    log.info("同步活动客户关系数据 result = {}", JSONObject.toJSONString(syncActivityClientRelationDataResponse));
                    //同步数据后的结果封装
                    CallApiRecordResponse callSyncActivityClientRelationDataResponse = new CallApiRecordResponse();
                    callSyncActivityClientRelationDataResponse.setRequestBody(JSONObject.toJSONString(syncActivityClientRelationDataRequest));
                    callSyncActivityClientRelationDataResponse.setOperateResult(syncActivityClientRelationDataResponse.getSuccess());
                    callSyncActivityClientRelationDataResponse.setTableName("ofs_activity_client_relation");
                    callSyncActivityClientRelationDataResponse.setMessage(syncActivityClientRelationDataResponse.getMessage());
                    callApiRecordResponses.add(callSyncActivityClientRelationDataResponse);
                    if (!syncActivityClientRelationDataResponse.getSuccess()) {
                        mnCrmCommSDO.setResultType(MnSAPStatus.ERROR.getCode());
                        ;
                        mnCrmCommSDO.setResultMessage(syncActivityClientRelationDataResponse.getMessage());
                    }
                });
            }
        }

        if (CollectionUtils.isNotEmpty(mnCrmIf007Request.getData().getActivityDetailItemRelation())) {

            List<ActivityDetailItemRelationDetail> activityDetailItemRelation = mnCrmIf007Request.getData().getActivityDetailItemRelation();

            //移除null 元素
            activityDetailItemRelation.remove(null);

            if (CollectionUtils.isNotEmpty(activityDetailItemRelation)) {
                activityDetailItemRelation.forEach(item -> {
                    SyncActivityTermItemRelationDataRequest syncActivityTermItemRelationDataRequest = new SyncActivityTermItemRelationDataRequest();
                    BeanUtils.copyProperties(item, syncActivityTermItemRelationDataRequest);
                    syncActivityTermItemRelationDataRequest.setItemId(SapAndCrmFieldDealUtils.generateIdField(item.getItemId()));
                    syncActivityTermItemRelationDataRequest.setFeatures(JSONObject.toJSONString(features));
                    SyncActivityTermItemRelationDataResponse syncActivityTermItemRelationDataResponse = crPriceCenterService.syncActivityTermItemRelationData(syncActivityTermItemRelationDataRequest);
                    log.info("同步活动原品关系数据 result = {}", JSONObject.toJSONString(syncActivityTermItemRelationDataResponse));

                    //同步数据后的结果封装
                    CallApiRecordResponse callSyncActivityTermItemRelationDataResponse = new CallApiRecordResponse();
                    callSyncActivityTermItemRelationDataResponse.setRequestBody(JSONObject.toJSONString(syncActivityTermItemRelationDataRequest));
                    callSyncActivityTermItemRelationDataResponse.setOperateResult(syncActivityTermItemRelationDataResponse.getSuccess());
                    callSyncActivityTermItemRelationDataResponse.setTableName("ofs_activity_term_item_relation");
                    callSyncActivityTermItemRelationDataResponse.setMessage(syncActivityTermItemRelationDataResponse.getMessage());
                    callApiRecordResponses.add(callSyncActivityTermItemRelationDataResponse);

                    if (!syncActivityTermItemRelationDataResponse.getSuccess()) {
                        mnCrmCommSDO.setResultType(MnSAPStatus.ERROR.getCode());
                        mnCrmCommSDO.setResultMessage(syncActivityTermItemRelationDataResponse.getMessage());
                    }

                });
            }
        }

        if (CollectionUtils.isNotEmpty(mnCrmIf007Request.getData().getActivityGiftRelation())) {

            List<ActivityGiftRelationDetail> activityGiftRelation = mnCrmIf007Request.getData().getActivityGiftRelation();

            //移除null 元素
            activityGiftRelation.remove(null);
            if (CollectionUtils.isNotEmpty(activityGiftRelation)) {
                activityGiftRelation.forEach(item -> {
                    SyncActivityTermGiftRelationDataRequest syncActivityTermGiftRelationDataRequest = new SyncActivityTermGiftRelationDataRequest();
                    BeanUtils.copyProperties(item, syncActivityTermGiftRelationDataRequest);
                    syncActivityTermGiftRelationDataRequest.setGiftId(SapAndCrmFieldDealUtils.generateIdField(item.getGiftId()));
                    syncActivityTermGiftRelationDataRequest.setFeatures(JSONObject.toJSONString(features));
                    SyncActivityTermGiftRelationDataResponse syncActivityTermGiftRelationDataResponse = crPriceCenterService.syncActivityTermGiftRelationData(syncActivityTermGiftRelationDataRequest);
                    log.info("同步活动赠品关系数据 result = {}", JSONObject.toJSONString(syncActivityTermGiftRelationDataResponse));

                    //同步数据后的结果封装
                    CallApiRecordResponse callSyncActivityTermGiftRelationDataResponse = new CallApiRecordResponse();
                    callSyncActivityTermGiftRelationDataResponse.setRequestBody(JSONObject.toJSONString(syncActivityTermGiftRelationDataRequest));
                    callSyncActivityTermGiftRelationDataResponse.setOperateResult(syncActivityTermGiftRelationDataResponse.getSuccess());
                    callSyncActivityTermGiftRelationDataResponse.setTableName("ofs_activity_term_gift_relation");
                    callSyncActivityTermGiftRelationDataResponse.setMessage(syncActivityTermGiftRelationDataResponse.getMessage());
                    callApiRecordResponses.add(callSyncActivityTermGiftRelationDataResponse);
                    if (!syncActivityTermGiftRelationDataResponse.getSuccess()) {
                        mnCrmCommSDO.setResultType(MnSAPStatus.ERROR.getCode());
                        mnCrmCommSDO.setResultMessage(syncActivityTermGiftRelationDataResponse.getMessage());
                    }
                });


            }


        }

        if (CollectionUtils.isNotEmpty(mnCrmIf007Request.getData().getSegmentedActivityTerm())) {
            List<SegmentedActivityTermDetail> segmentedActivityTerm = mnCrmIf007Request.getData().getSegmentedActivityTerm();
            //移除null 元素
            segmentedActivityTerm.remove(null);
            if (CollectionUtils.isNotEmpty(segmentedActivityTerm)) {

                segmentedActivityTerm.forEach(item -> {

                    SyncSegmentedActivityTermDataRequest syncSegmentedActivityTermDataRequest = new SyncSegmentedActivityTermDataRequest();

                    syncSegmentedActivityTermDataRequest.setActivityId(item.getActivityId());
                    syncSegmentedActivityTermDataRequest.setActivityTermId(item.getActivityTermId());
                    syncSegmentedActivityTermDataRequest.setSegmentedActivityId(item.getSegmentedActivityId());
                    syncSegmentedActivityTermDataRequest.setWithSendNotReUsable(item.getWithSendNotReUsable());
                    syncSegmentedActivityTermDataRequest.setSpecialOfferPrice(SapAndCrmFieldDealUtils.trimStr(item.getSpecialOfferPrice()));

                    if (StringUtils.isNotBlank(syncSegmentedActivityTermDataRequest.getSpecialOfferPrice())){
                        syncSegmentedActivityTermDataRequest.setSpecialOfferPrice(multiplyHundred(syncSegmentedActivityTermDataRequest.getSpecialOfferPrice()));
                    }
                    syncSegmentedActivityTermDataRequest.setSalesUnit(item.getSalesUnit());
                    syncSegmentedActivityTermDataRequest.setItemId(null);
                    syncSegmentedActivityTermDataRequest.setItemQuantity(SapAndCrmFieldDealUtils.toInteger(item.getItemQuantity()));
                    syncSegmentedActivityTermDataRequest.setGiftId(SapAndCrmFieldDealUtils.generateIdField(item.getGiftId()));
                    syncSegmentedActivityTermDataRequest.setGiftQuantity(SapAndCrmFieldDealUtils.toInteger(item.getGiftQuantity()));
                    syncSegmentedActivityTermDataRequest.setCurrency(item.getCurrency());
                    syncSegmentedActivityTermDataRequest.setFeatures(JSONObject.toJSONString(features));
                    SyncSegmentedActivityTermDataResponse syncSegmentedActivityTermDataResponse = crPriceCenterService.syncSegmentedActivityTermData(syncSegmentedActivityTermDataRequest);
                    log.info("同步坎级活动数据 result = {}", JSONObject.toJSONString(syncSegmentedActivityTermDataResponse));

                    //同步数据后的结果封装
                    CallApiRecordResponse callSyncSegmentedActivityTermDataResponse = new CallApiRecordResponse();
                    callSyncSegmentedActivityTermDataResponse.setRequestBody(JSONObject.toJSONString(syncSegmentedActivityTermDataRequest));
                    callSyncSegmentedActivityTermDataResponse.setOperateResult(syncSegmentedActivityTermDataResponse.getSuccess());
                    callSyncSegmentedActivityTermDataResponse.setTableName("ofs_segmented_activity_term");
                    callSyncSegmentedActivityTermDataResponse.setMessage(syncSegmentedActivityTermDataResponse.getMessage());
                    callApiRecordResponses.add(callSyncSegmentedActivityTermDataResponse);
                    if (!syncSegmentedActivityTermDataResponse.getSuccess()) {
                        mnCrmCommSDO.setResultType(MnSAPStatus.ERROR.getCode());
                        mnCrmCommSDO.setResultMessage(syncSegmentedActivityTermDataResponse.getMessage());
                    }
                });
            }



        }

        if (CollectionUtils.isNotEmpty(mnCrmIf007Request.getData().getOperateJournalFlow())) {
            List<OperateJournalFlowDetail> operateJournalFlow = mnCrmIf007Request.getData().getOperateJournalFlow();

            //移除null 元素
            operateJournalFlow.remove(null);
            if (CollectionUtils.isNotEmpty(operateJournalFlow)) {
                operateJournalFlow.forEach(item -> {
                    SyncOperateJournalFlowDataRequest syncOperateJournalFlowDataRequest = new SyncOperateJournalFlowDataRequest();
                    syncOperateJournalFlowDataRequest.setActivityId(item.getActivityId());
                    syncOperateJournalFlowDataRequest.setActivityTermId(item.getActivityTermId());
                    syncOperateJournalFlowDataRequest.setSegmentedActivityId(item.getSegmentedActivityId());
                    syncOperateJournalFlowDataRequest.setOperateJournalFlowId(item.getOperateJournalFlowId());
                    syncOperateJournalFlowDataRequest.setItemId(SapAndCrmFieldDealUtils.generateIdField(item.getItemId()));
                    syncOperateJournalFlowDataRequest.setItemQuantity(SapAndCrmFieldDealUtils.toInteger(item.getItemQuantity()));
                    syncOperateJournalFlowDataRequest.setGiftId(SapAndCrmFieldDealUtils.generateIdField(item.getGiftId()));
                    syncOperateJournalFlowDataRequest.setGiftQuantity(SapAndCrmFieldDealUtils.toInteger(item.getGiftQuantity()));
                    syncOperateJournalFlowDataRequest.setCommonGroup(item.getCommonGroup());
                    syncOperateJournalFlowDataRequest.setConditionPrice(SapAndCrmFieldDealUtils.trimStr(item.getConditionPrice()));
                    if (StringUtils.isNotBlank(syncOperateJournalFlowDataRequest.getConditionPrice())){
                        syncOperateJournalFlowDataRequest.setConditionPrice(multiplyHundred(syncOperateJournalFlowDataRequest.getConditionPrice()));
                    }
                    syncOperateJournalFlowDataRequest.setSegmentedActivityUnitPrice(SapAndCrmFieldDealUtils.trimStr(item.getSegmentedActivityUnitPrice()));
                    if (StringUtils.isNotBlank(syncOperateJournalFlowDataRequest.getSegmentedActivityUnitPrice())){
                        syncOperateJournalFlowDataRequest.setSegmentedActivityUnitPrice(multiplyHundred(syncOperateJournalFlowDataRequest.getSegmentedActivityUnitPrice()));
                    }
                    syncOperateJournalFlowDataRequest.setTailDifference(SapAndCrmFieldDealUtils.trimStr(item.getTailDifference()));
                    syncOperateJournalFlowDataRequest.setSalesUnit(item.getSalesUnit());
                    syncOperateJournalFlowDataRequest.setFeatures(JSONObject.toJSONString(features));
                    SyncOperateJournalFlowDataResponse syncOperateJournalFlowDataResponse = crPriceCenterService.syncOperateJournalFlowData(syncOperateJournalFlowDataRequest);
                    log.info("同步坎级活动流水数据 result = {}", JSONObject.toJSONString(syncOperateJournalFlowDataResponse));

                    //同步数据后的结果封装
                    CallApiRecordResponse callSyncOperateJournalFlowDataResponse = new CallApiRecordResponse();
                    callSyncOperateJournalFlowDataResponse.setRequestBody(JSONObject.toJSONString(syncOperateJournalFlowDataRequest));
                    callSyncOperateJournalFlowDataResponse.setOperateResult(syncOperateJournalFlowDataResponse.getSuccess());
                    callSyncOperateJournalFlowDataResponse.setTableName("ofs_operate_journal_flow");
                    callSyncOperateJournalFlowDataResponse.setMessage(syncOperateJournalFlowDataResponse.getMessage());
                    callApiRecordResponses.add(callSyncOperateJournalFlowDataResponse);
                    //返回数据

                    if (!syncOperateJournalFlowDataResponse.getSuccess()) {
                        mnCrmCommSDO.setResultType(MnSAPStatus.ERROR.getCode());
                        mnCrmCommSDO.setResultMessage(syncOperateJournalFlowDataResponse.getMessage());
                    }
                });
            }


        }

        //如果没有执行出错的记录
        if (StringUtils.isBlank(mnCrmCommSDO.getResultType())) {
            mnCrmCommSDO.setResultType(MnSAPStatus.SUCCESS.getCode());
        }
        if (StringUtils.isBlank(mnCrmCommSDO.getResultMessage())) {
            mnCrmCommSDO.setResultMessage("同步成功");
        }
        log.info("MnCrmIf007ServiceImpl_externalSynckLevelPromotionInfo => 执行结束入库结果 = {}",JSONObject.toJSONString(callApiRecordResponses));

        mnCrmCommResponse.setData(mnCrmCommSDO);
        return mnCrmCommResponse;
    }

    private String multiplyHundred(String specialOfferPrice) {

     return   new BigDecimal(specialOfferPrice).multiply(new BigDecimal(100)).setScale(0, RoundingMode.HALF_UP).toString();

    }
}
